﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using estudent.Models;
using System.Net;

namespace estudent.Controllers
{
    public class LoginController : Controller
    {

        //
        // GET: /Login/


        public ActionResult Index()
        {
            return View("Login");
        }


        //POST /Login/Sign
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Sign(FormCollection form)
        {
            //pregledam validacijo glede vnosa polj
            if (form["username"].Trim().Length == 0)
                ModelState.AddModelError("username", "Vpišite uporabniško ime.");
            else if (!Regex.IsMatch(form["username"], @"^([a-z]|[A-Z]|[0-9])+$"))
                ModelState.AddModelError("username", "Uporabniško ime je lahko sestavljeno samo iz črk in številk.");

            if (form["password"].Trim().Length == 0)
                ModelState.AddModelError("password", "Vpišite geslo.");
            else if (!Regex.IsMatch(form["password"], @"^([a-z]|[A-Z]|[0-9])+$"))
                ModelState.AddModelError("password", "Geslo je lahko sestavljeno samo iz črk in številk.");
            //

            //ce je vnos pravilen
            if (ModelState.IsValid)
            {
                //povezem na bazo preko entity model in pogledam login tabelo
                estudentEnt entities = new estudentEnt();
                string user = form["username"];
                string pass = form["password"];
                Prijava iskano = null;

                try
                {
                    iskano = entities.Prijavas.First(s => s.UpIme == user && s.Geslo == pass);
                    Session["Name"] = iskano.UpIme;
                    Session["Role"] = iskano.Vloga;
                    DateTime zadnji;

                    var orig = entities.Prijavas
                            .Where(p => p.UpIme == user)
                            .First();
                    if (orig.zadnjiDostop != null)
                        zadnji = orig.zadnjiDostop.Value.AddMinutes(3);
                    else
                        zadnji = DateTime.MinValue;


                    if (orig.zadnjiDostop != null && zadnji >= DateTime.Now && orig.stNapacnih != null && orig.stNapacnih >= 3 && orig.ip == Request.ServerVariables["REMOTE_ADDR"])
                    {
                        ModelState.AddModelError("", "Presegli ste 3 napačne prijave, zato morate počakati 3 minute od zadnje napačne prijave.");
                        return View("Login");
                    }
                    else
                    {

                        var spremen = entities.Prijavas
                            .Where(p => p.UpIme == user)
                            .First();

                        spremen.stNapacnih = 0;
                        spremen.ip = Request.ServerVariables["REMOTE_ADDR"];
                        entities.ApplyCurrentValues(orig.EntityKey.EntitySetName, spremen);
                        entities.SaveChanges();
                    }

                }
                catch (Exception)
                {
                    if (entities.Prijavas.Any(p => p.UpIme == user))
                    {
                        var orig = entities.Prijavas
                            .Where(p => p.UpIme == user)
                            .First();
                        var spremen = entities.Prijavas
                            .Where(p => p.UpIme == user)
                            .First();

                        spremen.zadnjiDostop = DateTime.Now;
                        if (spremen.stNapacnih == null)
                            spremen.stNapacnih = 1;
                        else
                            spremen.stNapacnih += 1;

                        entities.ApplyCurrentValues(orig.EntityKey.EntitySetName, spremen);
                        entities.SaveChanges();

                    }
                    else
                    {
                    }
                    ModelState.AddModelError("", "Prijava ni bila uspešna.");
                    return View("Login");
                }
                /*
                //samo temp
                iskano = new Prijava();
                iskano.UpIme = user;
                iskano.Geslo = pass;
                iskano.Vloga = "stud";
                Session["Name"] = iskano.UpIme;
                Session["Role"] = iskano.Vloga;
                //*/

                return RedirectToAction("Index", "Main");

            }
            return View("Login");
        }



    }
}
